package com.bds.btcdc.api.impl;

import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.adapter.huobi.trade.service.HuobiTradeService;
import com.bds.btcdc.adapter.okcoin.service.OkCoinTradeService;
import com.bds.btcdc.api.TradeService;
import com.bds.btcdc.api.model.AccountInfo;
import com.bds.btcdc.config.NutzDaoConfig;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.model.OrderRecord;
import com.bds.btcdc.model.UserKeys;
import com.bds.btcdc.service.PairConverterService;
import com.bds.btcdc.service.UserKeysService;
import com.bds.btcdc.adapter.okex.trade.service.OkexTradeService;
import com.bds.btcdc.adapter.zb.service.ZBTradeService;
import com.bds.btcdc.util.Const;
import com.bds.btcdc.util.EhcacheUtils;
import com.bds.btcdc.api.model.Order;
import org.nutz.dao.Cnd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.DecimalFormat;
import java.util.*;

/**
 * @author: kevin
 * @date: 2018/5/7
 * @description:
 */
@Service("TradeService")
public class TradeServiceImpl implements TradeService {
    private Logger logger= LoggerFactory.getLogger(getClass());
    private DecimalFormat df = new DecimalFormat(Const.END_WITH_COUNT);
    @Autowired
    private NutzDaoConfig dao;
    @Autowired
    private ZBTradeService zBTradeService;
    @Autowired
    private OkCoinTradeService okCoinTradeService;
    @Autowired
    private OkexTradeService okexTradeService;
    @Autowired
    private HuobiTradeService huobiTradeService;
    @Autowired
    private UserKeysService userKeysService;
    @Autowired
    private PairConverterService pairConverterService;

    @Override
    public Result makeOrder(Order order){
        Result res = new Result();
        if(!orderVolidate(order)){
            res.setResult(Const.FAIL,"委托下单的数据不完整！！！");
        }else{
            switch (order.getExchange().toUpperCase()){
                case Const.ZB.EXCHANGE://zb交易所的委托下单
                    res = zBTradeService.makeOrder(order);
                    break;
                case Const.HUOBI.EXCHANGE:
                    res = huobiTradeService.makeOrder(order);
                    break;
                case Const.OKEX.EXCHANGE:
                    res = okexTradeService.makeOrder(order);
                    break;
                //...其他交易所
                default:
                    break;

            }
        }

        return res;
    }

    @Override
    public Result cancelOrder(long userId, String orderId) {
        return null;
    }

    @Override
    public Result getOrders(long userId, List<String> orderIds) {
        Result rst = new Result();
        List<Result> list=new ArrayList<>();//多个订单的状态集合
        if(userId==0||orderIds==null||orderIds.size()==0){
            rst.setResult(Const.FAIL,"查询参数不完整！");
        }else{
            //去库中查找orderId对应的第三方ID
            for (int i = 0; i <orderIds.size(); i++) {
                String order_id=orderIds.get(i);
                OrderRecord record=dao.query(OrderRecord.class,Cnd.where("order_no","=",order_id)).get(0);
                String exchange=record.getExchange();
                //第三方订单ID
                String api_id=record.getApi_id();
                switch (exchange){
                    case Const.HUOBI.EXCHANGE:
                        Result r=huobiTradeService.getOrder(userId,api_id);
                        list.add(r);
                        break;
                    default:
                        rst.setResult(Const.FAIL,"没有该交易所信息");
                        break;
                }
            }
            rst.setResult(Const.SUC,list);
        }
        return rst;
    }

    /**
     * 查询用户各个交易所的资产信息
     * @param userId
     * @return AccountInfo
     */
    @Override
    public Result getAccount(long userId){
        Result res=new Result();
        List<UserKeys> userKeys=null;
        String cache = EhcacheUtils.getInstance().getCache(String.valueOf(userId));
        if(StringUtils.isEmpty(cache)){
            try {
                userKeys = userKeysService.getByUserId(userId);
            }catch (Exception e){
                e.printStackTrace();
            }
            if(!CollectionUtils.isEmpty(userKeys)) {
                EhcacheUtils.getInstance().putCache(String.valueOf(userId), JSONObject.toJSONString(userKeys));
            }
        }else{
            userKeys = JSONObject.parseArray(cache, UserKeys.class);
        }
        List<AccountInfo> accountInfos=new ArrayList<>();
        if(!CollectionUtils.isEmpty(userKeys)){
            for(UserKeys keys:userKeys) {
                try {
                    if (!StringUtils.isEmpty(keys.getAccess_key())
                            && !StringUtils.isEmpty(keys.getSecret_key())) {
                        AccountInfo accountInfo = null;
                        long start = System.currentTimeMillis();
                        switch (keys.getExchange().toUpperCase()) {
                            case Const.ZB.EXCHANGE://获取zb交易所的 资产情况
                                res = zBTradeService.getAccount(keys);
                                break;
                            case Const.OKEX.EXCHANGE://获取okex交易所的 资产情况
                                res = okexTradeService.getAccount(keys);
                                break;
                            case Const.HUOBI.EXCHANGE:
                                res = huobiTradeService.getAccount(keys);
                                break;
                            default:
                                res.setResult(Const.FAIL, "暂时没有该交易所的数据：" + keys.getExchange());
                                break;
                        }
                        long end = System.currentTimeMillis();
                        logger.info(">>>>>>>>>>>>>>获取"+keys.getExchange()+"交易所的 资产情况 耗时："+(end-start));
                        if (res.getCode() == Const.SUC) {
                            accountInfo = JSONObject.parseObject(JSONObject.toJSONString(res.getData()), AccountInfo.class);
                            accountInfos.add(accountInfo);
                        }
                    } else {
                        res.setResult(Const.FAIL, "access_key,secret_key数据不完整！请在“个人设置”,“API设置”中添加");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    continue;//下一个userkeys
                }
            }
        }else{
            res.setResult(Const.FAIL, "没有任何api设置信息，请在“个人设置”,“API设置”中添加");
        }
        res.setCode(Const.SUC);
        res.setData(JSONObject.toJSONString(accountInfos));

        return res;
    }

    private Boolean orderVolidate(Order order){
        if(StringUtils.isEmpty(order.getExchange())
            ||order.getNum()==0.0
            ||order.getPrice()==0.0
            ||StringUtils.isEmpty(order.getSymbol())
            ||StringUtils.isEmpty(order.getType())
            ||StringUtils.isEmpty(order.getUserId())){
            return false;
        }
        return true;
    }

}
